/*
 * Copyright 2014 Walter Lütgenau.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package offset.nodes.client.vdialog.view.remove;

import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.text.Element;
import offset.nodes.client.dialog.navigation.model.DialogAppletContext;
import offset.nodes.client.dialog.remove.model.HasReferences;
import offset.nodes.client.dialog.remove.model.RemoveNode;
import offset.nodes.client.dialog.remove.view.RemoveNodeApplet;

/**
 *
 * @author Walter Lütgenau
 */
public class RemoveRowNodeApplet extends RemoveNodeApplet {
    /** The uuid as encoded as extended attribute */
    public static final String ATT_ID = "n-id";
    
    public void startUI() {
        try {
            String uuid = getUuidOfRowNode();
            System.out.println("RemoveRowNodeApplet: " + uuid);
            
            HasReferences.Request hasReferencesRequest = new HasReferences.Request();    
            hasReferencesRequest.setUuid(uuid);
            
            HasReferences.Response response = (HasReferences.Response) getModel().sendRequest(hasReferencesRequest);
            
            if (response.getReferences() != HasReferences.Response.ReferenceResult.noReference) {
                showReferencesDialog(response.getReferences());
                return;
            } else {
                if (showRemoveConfirmationDialog() == JOptionPane.OK_OPTION) {
                    RemoveNode.Request removeNodeRequest = new RemoveNode.Request();
                    removeNodeRequest.setUuid(uuid);
                    RemoveNode.Response removeNodeResponse = (RemoveNode.Response) getModel().sendRequest(removeNodeRequest);
                }
            }

            URL url = new URL(getRepository() + "/" + getPath());
            getAppletContext().showDocument(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * From the calling node, determine the uuid of the row.
     * 
     * @return the uuid
     */
    protected String getUuidOfRowNode() {
        DialogAppletContext context = (DialogAppletContext) getAppletContext();
        
        Element row = context.getCallingNode().getParentElement();
        String result = (String) row.getAttributes().getAttribute(ATT_ID);
        
        return result;
    }
    
}
